﻿using Dapper;
using DataServer.ApplicationLib.Controls;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using Swimj.DataCore;

namespace DataServer.ApplicationLib.Rules
{
    public class TextBoxModelVerifyFactory
    {
        public static IControlModelVerify? CreateTextBoxVerify(CreateCtrlVerifyInput input)
        {
            IControlModelVerify? verfiyObj = null;

            if (!string.IsNullOrEmpty(input.ControlContent))
            {
                var ctlModel = JsonConvert.DeserializeObject<ControlTextBoxModel>(input.ControlContent);
                if (ctlModel != null)
                {
                    ctlModel.TargetFieldColumn = input.TargetFieldColumn;

                    switch (input.CheckWay)
                    {
                        case DataCheckWay.InDB:
                            verfiyObj = new DbTextBoxModelVerify(ctlModel);
                            break;
                        default:
                            verfiyObj = new DefaultTextBoxModelVerify(ctlModel);
                            break;
                    }
                }
            }
            return verfiyObj;
        }
    }

    public class DbTextBoxModelVerify : ControlModelVerifyBase<ControlTextBoxModel>, IControlModelVerify
    {
        public DbTextBoxModelVerify(ControlTextBoxModel model)
        {
            this.Model = model;
        }

        #region IControlModelVerify Members

        public VerifyRuleResult Verify(RuleContext context)
        {
            VerifyRuleResult result = new VerifyRuleResult();
            var targetField = context.ConfigFieldInfos.Where(f => f.ValueColumnMap == this.Model.TargetFieldColumn).FirstOrDefault();
            if (targetField != null &&
                (this.Model.MaxLength > 0 || !string.IsNullOrEmpty(this.Model.RegexExp)))
            {
                string invalidMsg = $"{targetField.FieldName}";
                string checkCond = string.Empty;
                if (this.Model.MaxLength > 0)
                {
                    invalidMsg += $"的长度超过{this.Model.MaxLength}";
                    checkCond += string.Format("LENGTH({0})>{1}", targetField.ValueColumnMap, this.Model.MaxLength);
                }

                if (!string.IsNullOrEmpty(this.Model.RegexExp))
                {
                    invalidMsg += $"{(this.Model.MaxLength > 0 ? "或" : string.Empty)}不满足{(string.IsNullOrEmpty(this.Model.RegexExpDesc) == true ? this.Model.RegexExp : this.Model.RegexExpDesc)}";
                    checkCond += string.Format(" OR NOT REGEXP_LIKE({0},'{1}','i') ", targetField.ValueColumnMap, this.Model.RegexExp);
                }

                string updateSql = string.Format(@"UPDATE  " + ConfigDataTableCheck.TableName + @" 
                                                   SET ISVALID = '{5}', MESSAGE = CONCAT(COALESCE(MESSAGE,''), '{4}')
                                                 WHERE ConfigId = '{0}'
                                                   AND RequestId = '{1}'
                                                   AND {2} IS NOT NULL
                                                   AND ({3}) ", context.ConfigInfo.Id, context.RequestId, targetField.ValueColumnMap, checkCond, invalidMsg, VerifyResultColumns.InvalidVal);

                var unitOfWork = context.ServiceProvider.GetRequiredService<IUnitOfWork>();
                int updatedRows = unitOfWork.Connection.Execute(updateSql);
                if (updatedRows > 0)
                {
                    result.Message = string.Format("{0} 有数据的长度超过{1}或不满足{2}", targetField.DisplayName, this.Model.MaxLength, (string.IsNullOrEmpty(this.Model.RegexExpDesc) == true ? this.Model.RegexExp : this.Model.RegexExpDesc));
                    result.IsValid = false;
                }
            }
            return result;
        }

        #endregion
    }

    public class DefaultTextBoxModelVerify : ControlModelVerifyBase<ControlTextBoxModel>, IControlModelVerify
    {
        public DefaultTextBoxModelVerify(ControlTextBoxModel model)
        {
            this.Model = model;
        }

        #region IControlModelVerify Members

        public VerifyRuleResult Verify(RuleContext context)
        {
            VerifyRuleResult result = new VerifyRuleResult();
            //var targetField = context.FieldList.Where(f => f.ValueMapColumn == this.Model.TargetFieldColumn).FirstOrDefault();

            //if (null != targetField)
            //{
            //    for (int i = 0; i < context.TargetData.Rows.Count; i++)
            //    {
            //        DataRow row = context.TargetData.Rows[i];
            //        var val = row[this.Model.TargetFieldColumn];
            //        if (null != val && !string.IsNullOrWhiteSpace(val.ToString()))
            //        {
            //            bool isValid = true;
            //            string msg = targetField.DisplayName + ":";
            //            if (val.ToString().Length > this.Model.MaxLength)
            //            {
            //                isValid = false;
            //                msg += "超过了最大长度：" + this.Model.MaxLength + ";";
            //            }
            //            if (false == string.IsNullOrWhiteSpace(this.Model.RegexValue) && false == Regex.IsMatch(GetValString(val), this.Model.RegexValue))
            //            {
            //                isValid = false;
            //                msg += "不符合正则表达式的要求：" + (string.IsNullOrEmpty(this.Model.RegexValueDesc) == true ? this.Model.RegexValue : this.Model.RegexValueDesc) + ";";
            //            }
            //            if (!isValid)
            //            {
            //                result.IsValid = false;
            //                row[VerifyResultColumns.IsValid] = VerifyResultColumns.InvalidVal;
            //                row[VerifyResultColumns.Message] = row[VerifyResultColumns.Message].ToString() + msg;
            //            }
            //        }
            //    }
            //    if (!result.IsValid)
            //    {
            //        result.Message = string.Format("{0} 有数据不符合长度或格式要求;", targetField.DisplayName);
            //    }
            //}

            return result;

        }

        #endregion

        //private string GetValString(object val)
        //{
        //    string retStr = string.Empty;
        //    if (val.GetType() == typeof(double))
        //    {
        //        retStr = val.ToSafeDouble(0).ToString("0.####################");
        //        retStr = retStr.TrimEnd('.');
        //    }
        //    else
        //    {
        //        retStr = val.ToString();
        //    }
        //    return retStr;
        //}
    }
}
